package com.example.springmvc.controller;

import com.example.springmvc.exception.MyException;
import com.example.springmvc.pojo.Item;
import com.example.springmvc.pojo.User;
import com.example.springmvc.service.IItemService;
import com.example.springmvc.service.UserService;
import com.example.springmvc.vo.QueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

// 控制器 注解
@Controller
public class ItemController {


//    // 请求映射地址注解
//    @RequestMapping("/itemList.action")
//    public ModelAndView itemList()
//    {
//        List<Item> list = new ArrayList<>();
//        list.add(new Item(1, "1vivo X20", 2399, new Date(), "质量好！1"));
//        list.add(new Item(2, "2vivo X20", 2399, new Date(), "质量好！2"));
//        list.add(new Item(3, "3vivo X20", 2399, new Date(), "质量好！3"));
//        list.add(new Item(4, "4vivo X20", 2399, new Date(), "质量好！4"));
//        list.add(new Item(5, "5vivo X20", 2399, new Date(), "质量好！5"));
//        list.add(new Item(6, "6vivo X20", 2399, new Date(), "质量好！6"));
//
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("itemList",list);
////        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
//        modelAndView.setViewName("itemList");
//
//        return modelAndView;
//    }


    @Autowired
    private IItemService itemService;
    @Autowired
    private UserService userService;

    // 请求映射地址注解
    @RequestMapping("/itemList2.action")
    public ModelAndView itemList2()
    {
        List<Item> list=itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    //    // 3. springmvc默认支持的参数类型
//    // HttpServletRequest
//    // HttpServletResponse resp
//    // HttpSession session
//    @RequestMapping("/itemEdit.action")
//    public ModelAndView itemEdit(HttpServletResponse resp, HttpSession session, HttpServletRequest req)
//    {
//        String idStr = req.getParameter("id");
//        int id = Integer.parseInt(idStr);
//
//        Item item = itemService.queryItemById(id);
//
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("item",item);
//        modelAndView.setViewName("editItem");
//
//        return modelAndView;
//    }

    //     3. 传入Model或MadelMap 替代 创建ModelAndView
//    @RequestMapping("/itemEdit.action")
//    public String itemEdit(HttpServletRequest req, Model model)
//    {
//        String idStr = req.getParameter("id");
//        int id = Integer.parseInt(idStr);
//
//        Item item = itemService.queryItemById(id);
//        model.addAttribute("item",item);
//
//        return "editItem";
//    }

    // 4. 简单类型绑定参数
    // @RequestParam 指定绑定的参数名 默认值
    @RequestMapping("/itemEdit.action")
    public String itemEdit(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id, Model model)
    {
        Item item = itemService.queryItemById(id);
        model.addAttribute("item",item);

        return "editItem";
    }

    // 5. 绑定pojo
    @RequestMapping("/updateItem.action")
    public String updateItem(Item item)
    {
        itemService.updateItemById(item);

        return "success";
    }
    // 6. 绑定包装pojo
    @RequestMapping("queryItem.action")
    public String queryItem(QueryVO queryVO)
    {
        System.out.println(queryVO.getItem().getId());
        System.out.println(queryVO.getItem().getName());

        System.out.println(Arrays.toString(queryVO.getIds()));

        for(Item i:queryVO.getItemList())
        {
            System.out.println(i);
        }

        return "success";
    }

    @RequestMapping("/itemList3.action")
    public ModelAndView itemList3()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList3");

        return modelAndView;
    }


    // 9. RequestMapping
//    @RequestMapping("/itemList2.action")
//    @RequestMapping(value="/itemList2.action")
    @RequestMapping(value={"/itemList4.action","itemListAll.action"})
    public ModelAndView itemList4()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    @RequestMapping(value="/itemList5.action",method = RequestMethod.POST)
    public ModelAndView itemList5()
    {
        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
//        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    //  10. 返回值可以是void

    @RequestMapping("/itemList6.action")
    public void itemList6(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {

        // 请求转发
        req.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(req,resp);

        // 跳转
//        resp.sendRedirect("/item/itemList2.action");

        // 直接打印
//        resp.getWriter().println("ok");

    }


    // 11. 通过返回字符串 redirect:/ 重定向
    /**
     * 更新商品
     *
     * @param item
     * @return
     */
//    @RequestMapping("/updateItem2.action")
//    public String updateItemById2(Item item) {
//        // 更新商品
//        this.itemService.updateItemById(item);
//
//        // 修改商品成功后，重定向到商品编辑页面
//        // 重定向后浏览器地址栏变更为重定向的地址，
//        // 重定向相当于执行了新的request和response，所以之前的请求参数都会丢失
//        // 如果要指定请求参数，需要在重定向的url后面添加 ?itemId=1 这样的请求参数
//        return "redirect:/item/itemEdit.action?itemId=" + item.getId();
//    }


    // 12. 测试出现异常
    @RequestMapping(value="/itemList12.action")
    public ModelAndView itemList12() throws MyException
    {
        int r = (int)(Math.random()*4);
        if(r==0)
        {
            int x = 1/0;
        }
        else if(r==1)
        {
            int[] arr = {1,2,3};
            System.out.println(arr[3]);
        }
        else if(r==2)
        {
            throw new MyException("心情不好");
        }

        List<Item> list = itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",list);
        modelAndView.setViewName("itemList");

        return modelAndView;
    }


    // 测试文件上传
    @RequestMapping("/updateItem3.action")
    public String updateItemById3(Item item, MultipartFile pictureFile) throws IOException {

        // 图片上传
        // 设置图片名称，不能重复，可以使用uuid
        String picName = UUID.randomUUID().toString();

        // 获取文件名
        String oriName = pictureFile.getOriginalFilename();
        // 获取图片后缀
        String extName = oriName.substring(oriName.lastIndexOf("."));

        // 开始上传
        pictureFile.transferTo(new File("D:/pic/" + picName + extName));

        // 设置图片名到商品中
        item.setPic(picName + extName);
        // ---------------------------------------------
        // 更新商品
        this.itemService.updateItemById(item);

        return "forward:/itemEdit.action?id="+item.getId();
    }


    // @RequestBody     提交过来的请求参数是json数据
    // @ResponseBody    返回的是json数据


    // testJson.action?id=1&name=台式机&price=999.99
    // testJson.action
    // {
    //     "id":1,
    //     "name":“台式机"
    //     "price":9999
    // }
    /**
     * 测试json的交互
     * @param item
     * @return
     */
    @RequestMapping("testJson.action")
    @ResponseBody
    public  Item testJson(@RequestBody Item item)
    {
        System.out.println("item:"+item);
        return item;
    }


    // http://127.0.0.1:8080/item/1
    // @PathVariable() 路径获取参数
    /**
     * 使用RESTful风格开发接口，实现根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("item/{id}")
    @ResponseBody
    public Item queryItemById(@PathVariable() Integer id) {
        Item item = this.itemService.queryItemById(id);
        return item;
    }

    @GetMapping("item/")
    @ResponseBody
    public List<Item> queryItems()
    {
        List<Item> items = this.itemService.queryItemList();
        return items;
    }

    @PostMapping("item/")
    @ResponseBody
    public Item addItem(@RequestBody Item item)
    {
        this.itemService.addItem(item);
        return item;
    }

    @PutMapping("item/")
    @ResponseBody
    public Item updateItem3(@RequestBody Item item)
    {
        this.itemService.updateItemById(item);
        return item;
    }

    @DeleteMapping("item/{id}")
    @ResponseBody
    public String deleteItemById(@PathVariable() Integer id)
    {
        this.itemService.deleteById(id);
        return "ok";
    }


    @RequestMapping("/userList1.action")
    public ModelAndView userList1()
    {
        List<User> list=userService.queryUserList();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList",list);
       // modelAndView.setViewName("/WEB-INF/jsp/userList.jsp");
        modelAndView.setViewName("userList");

        return modelAndView;
    }

    @RequestMapping("/userEdit.action")
    public String userEdit(@RequestParam(value = "userId", required = true, defaultValue = "1") Integer id, Model model)
    {
        User user = userService.queryUserById(id);
        model.addAttribute("user",user);

        return "editUser";
    }

    @RequestMapping("/updateUser.action")
    public String updateUser(User user)
    {
        userService.updateUserById(user);

        return "success";
    }

    @RequestMapping("queryUser.action")
    public String queryUser(QueryVO queryVO)
    {
        System.out.println(queryVO.getUser().getUsername());
        System.out.println(queryVO.getItem().getName());

        //  System.out.println(Arrays.toString(queryVO.getIds()));
//
//        for(User u:queryVO.getUserList())
//        {
//            System.out.println(u);
//        }

        return "success";
    }
}

